package com.muyu.danmo.service.impl;


import com.alibaba.nacos.common.utils.CollectionUtils;
import com.muyu.common.core.domain.Result;
import com.muyu.common.core.utils.DateUtils;
import com.muyu.common.core.utils.StringUtils;
import com.muyu.common.security.utils.SecurityUtils;
import com.muyu.common.system.domain.LoginUser;
import com.muyu.danmo.domain.*;
import com.muyu.danmo.mapper.DanmoMountFavoriteMapper;
import com.muyu.danmo.mapper.DanmoMountMessageMapper;
import com.muyu.danmo.service.IDanmoMountMessageService;
import com.muyu.danmo.service.IDanmoMountTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

import static com.muyu.common.core.domain.Result.warn;

/**
 * 装裱信息Service业务层处理
 *
 * @author yangle
 * @date 2024-10-14
 */
@Service
public class DanmoMountMessageServiceImpl implements IDanmoMountMessageService {
    @Autowired
    private DanmoMountMessageMapper danmoMountMessageMapper;

    @Autowired
    private DanmoMountFavoriteMapper danmoMountFavoriteMapper;

    /**
     * 查询装裱信息
     *
     * @param id 装裱信息主键
     * @return 装裱信息
     */
    @Override
    public DanmoMountMessage selectDanmoMountMessageById(Long id) {
        DanmoMountMessage danmoMountMessage = danmoMountMessageMapper.selectDanmoMountMessageById(id);
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (danmoMountMessage != null && !danmoMountMessage.getUserId().equals(loginUser.getUserid())){
            danmoMountMessage.setBusinessLicense(null);
            danmoMountMessage.setFrontOfIdCard(null);
            danmoMountMessage.setReverseSideOfIdCard(null);
        }
//        Long userid = loginUser.getUserid();
//        danmoMountMessage.setUserId(userid);
        danmoMountMessage.setViews(danmoMountMessage.getViews() + 1);
        boolean b = danmoMountFavoriteMapper.existsByUserIdAndPrintingClassId(loginUser.getUserid(), id);
        System.out.println(b);
        if (danmoMountFavoriteMapper.existsByUserIdAndPrintingClassIdLike(loginUser.getUserid(), id)) {
            danmoMountMessage.setPraise("已点赞");
        }
        if (danmoMountFavoriteMapper.existsByUserIdAndPrintingClassId(loginUser.getUserid(), id)) {
            danmoMountMessage.setIsCollection("已收藏");
        }
        danmoMountMessageMapper.updateDanmoMountMessage(danmoMountMessage);
        return danmoMountMessage;
    }

    /**
     * 查询装裱信息列表
     *
     * @param danmoMountMessage 装裱信息
     * @return 装裱信息
     */
    @Override
    public List<DanmoMountMessage> selectDanmoMountMessageList(DanmoMountMessage danmoMountMessage) {

        return danmoMountMessageMapper.selectDanmoMountMessageList(danmoMountMessage);
    }

    @Autowired
    private IDanmoMountTypeService danmoMountTypeService;
    /**
     * 新增装裱信息
     *
     * @param danmoMountMessage 装裱信息
     * @return 结果
     */
    @Transactional
    @Override
    public Result insertDanmoMountMessage(DanmoMountMessage danmoMountMessage) {
        try {
//            LoginUser loginUser = SecurityUtils.getLoginUser();
//            if (loginUser == null) {
//                return warn("请登录");
//            }
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (loginUser==null){
                return Result.notLoggedIn("请登录");
            }
            Long userid = loginUser.getUserid();
            Result result = validateDanmoTrainingInformation(danmoMountMessage);
            if (result != null) {
                return result;
            }
            DanmoMountMessage danmoMountMessage1 = new DanmoMountMessage();
            danmoMountMessage1.setUserId(userid);
/*            List<DanmoMountMessage> danmoMountMessages = danmoMountMessageMapper.selectDanmoMountMessageList(danmoMountMessage1);
            if (danmoMountMessages.size() > 0) {
                return Result.error("您已发布过装裱信息，请勿重复发布");
            }*/
            danmoMountMessage.setViews(0L);
            danmoMountMessage.setStatus(0L);
            danmoMountMessage.setAmountPraise(0L);
            danmoMountMessage.setUserId(userid);
            danmoMountMessage.setCreateTime(DateUtils.getNowDate());
            danmoMountMessageMapper.insertDanmoMountMessage(danmoMountMessage);

            List<DanmoMountType> danmoMountTypes = danmoMountMessage.getDanmoMountTypes();
//            if (danmoMountTypes != null && danmoMountTypes.size() > 0) {
//                for (DanmoMountType danmoMountType : danmoMountTypes) {
//                    danmoMountType.setMessageId(danmoMountMessage.getId());
//                    danmoMountTypeService.insertDanmoMountType(danmoMountType);
//                }
//            }

            Long danmoMountMessageId = danmoMountMessage.getId();
            // 第二步：为 DanmoPrintingDoor 和 DanmoPrintingWorks 和  InteriorPhotos 设置 messageId
            setMountMessageIdForDoors(danmoMountMessage.getDanmoMountDoors(), danmoMountMessageId);
            setMountMessageIdForWorks(danmoMountMessage.getDanmoMountWorks(), danmoMountMessageId);
            setMountMessageIdInteriorPhotos(danmoMountMessage.getDanmoMountInteriorList(), danmoMountMessageId);
            setMountMessageIdDanmoMountTypess(danmoMountMessage.getDanmoMountTypes(), danmoMountMessageId);

            // 第三步：插入其他相关数据
            insertDanmoMountDoors(danmoMountMessage.getDanmoMountDoors());
            insertDanmoMountInteriorList(danmoMountMessage.getDanmoMountInteriorList());
            insertDanmoMountWorks(danmoMountMessage.getDanmoMountWorks());
            insertDanmoMountTypes(danmoMountMessage.getDanmoMountTypes());


            return Result.success(danmoMountMessage, "添加成功");
//            insertDanmoMountImages(danmoMountMessage);
        } catch (Exception e) {
            return Result.error("添加失败");
        }


    }

    private void insertDanmoMountTypes(List<DanmoMountType> danmoMountTypes) {
        if (danmoMountTypes != null && !danmoMountTypes.isEmpty()) {
            danmoMountMessageMapper.insertDanmoMounttypes(danmoMountTypes);
        }
    }

    private void setMountMessageIdDanmoMountTypess(List<DanmoMountType> danmoMountTypes, Long danmoMountMessageId) {
        if (danmoMountTypes != null && !danmoMountTypes.isEmpty()) {
            for (DanmoMountType danmoMountType : danmoMountTypes) {
                danmoMountType.setId(null);
                danmoMountType.setMessageId(danmoMountMessageId);
            }
        }
    }

    private Result validateDanmoTrainingInformation(DanmoMountMessage danmoMountMessage) {
        if (danmoMountMessage == null) {
            return Result.error("信息不能为空");
        }
        if (danmoMountMessage.getTitle() == null || danmoMountMessage.getTitle().isEmpty()) {
            return Result.error("请输入标题");
        }
        if (danmoMountMessage.getIntroduction() == null || danmoMountMessage.getIntroduction().isEmpty()) {
            return Result.error("请输入店铺介绍");
        }
        if (danmoMountMessage.getStartTime() == null || danmoMountMessage.getStartTime().isEmpty()) {
            return Result.error("请输入营业时间");
        }
        if (danmoMountMessage.getContactInfo() == null || danmoMountMessage.getContactInfo().isEmpty()) {
            return Result.error("请输入联系方式");
        }
        if (danmoMountMessage.getAddress() == null || danmoMountMessage.getAddress().isEmpty()) {
            return Result.error("请输入店铺地址信息");
        }
        if (danmoMountMessage.getProvince() == null ||
                danmoMountMessage.getProvince().isEmpty() ||
                danmoMountMessage.getCitycode() == null ||
                danmoMountMessage.getCitycode().isEmpty() ||
                danmoMountMessage.getCountycode() == null ||
                danmoMountMessage.getCountycode().isEmpty()) {
            return Result.error("省市区不能为空");
        }
//        for (DanmoMountDoor danmoMountDoor : danmoMountMessage.getDanmoMountDoors()) {
//            if (danmoMountDoor.getPhotosUrl() == null || danmoMountDoor.getPhotosUrl().isEmpty()){
//                return Result.error("请上传门头图片");
//            }
//        }
        return null;
    }

    private void insertDanmoMountWorks(List<DanmoMountWorks> danmoMountWorks) {
        if (danmoMountWorks != null && !danmoMountWorks.isEmpty()) {
            danmoMountMessageMapper.insertDanmoMountWorks(danmoMountWorks);
        }
    }

    private void insertDanmoMountInteriorList(List<DanmoMountInterior> danmoMountInteriorList) {
        if (danmoMountInteriorList != null && !danmoMountInteriorList.isEmpty()) {
            danmoMountMessageMapper.insertDanmoMountInteriorList(danmoMountInteriorList);
        }
    }

    private void insertDanmoMountDoors(List<DanmoMountDoor> danmoMountDoors) {
        if (danmoMountDoors != null && !danmoMountDoors.isEmpty()) {

            danmoMountMessageMapper.insertDanmoMountDoors(danmoMountDoors);
        }
    }

    private void setMountMessageIdInteriorPhotos(List<DanmoMountInterior> danmoMountInteriorList, Long danmoMountMessageId) {
        if (danmoMountInteriorList != null && !danmoMountInteriorList.isEmpty()) {
            for (DanmoMountInterior danmoMountInterior : danmoMountInteriorList) {
                danmoMountInterior.setMessageId(danmoMountMessageId);
            }
        }
    }


    private void setMountMessageIdForWorks(List<DanmoMountWorks> danmoMountWorks, Long danmoMountMessageId) {
        if (danmoMountWorks != null && !danmoMountWorks.isEmpty()) {
            for (DanmoMountWorks danmoMountWork : danmoMountWorks) {
                danmoMountWork.setMessageId(danmoMountMessageId);
            }
        }
    }

    private void setMountMessageIdForDoors(List<DanmoMountDoor> danmoMountDoors, Long danmoMountMessageId) {
        if (danmoMountDoors != null && !danmoMountDoors.isEmpty()) {
            for (DanmoMountDoor danmoMountDoor : danmoMountDoors) {
                danmoMountDoor.setMessageId(danmoMountMessageId);
            }
        }
    }

    /**
     * 修改装裱信息
     *
     * @param danmoMountMessage 装裱信息
     * @return 结果
     */
    @Transactional
    @Override
    public Result updateDanmoMountMessage(DanmoMountMessage danmoMountMessage) {
        try {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (loginUser == null) {
                return warn("请登录");
            }
            Long userid = loginUser.getUserid();
            Result result = validateDanmoTrainingInformation(danmoMountMessage);
            if (result != null) {
                return result;
            }

            danmoMountMessage.setUpdateTime(DateUtils.getNowDate());
            danmoMountMessageMapper.updateDanmoMountMessage(danmoMountMessage);

            Long danmoMountMessageId = danmoMountMessage.getId();

            deleteOldRelatedData(danmoMountMessageId);

            // 第二步：为 DanmoPrintingDoor 和 DanmoPrintingWorks 和  InteriorPhotos 设置 messageId
            setMountMessageIdForDoors(danmoMountMessage.getDanmoMountDoors(), danmoMountMessageId);
            setMountMessageIdForWorks(danmoMountMessage.getDanmoMountWorks(), danmoMountMessageId);
            setMountMessageIdInteriorPhotos(danmoMountMessage.getDanmoMountInteriorList(), danmoMountMessageId);
            setMountMessageIdDanmoMountTypess(danmoMountMessage.getDanmoMountTypes(), danmoMountMessageId);

            // 第三步：插入其他相关数据
            insertDanmoMountDoors(danmoMountMessage.getDanmoMountDoors());
            insertDanmoMountInteriorList(danmoMountMessage.getDanmoMountInteriorList());
            insertDanmoMountWorks(danmoMountMessage.getDanmoMountWorks());
            insertDanmoMountTypes(danmoMountMessage.getDanmoMountTypes());
//            danmoMountMessageMapper.deleteDanmoMountImagesByMountId(danmoMountMessage.getId());
//            insertDanmoMountImages(danmoMountMessage);
        } catch (Exception e) {
            return Result.error("修改失败");
        }
        return Result.success(danmoMountMessage,"修改成功");
    }

    private void deleteOldRelatedData(Long danmoMountMessageId) {
        List<Long> danmoDoorIdList = danmoMountMessageMapper.selectDanmoMountDoorList(danmoMountMessageId);
        if (CollectionUtils.isNotEmpty(danmoDoorIdList)) {
            danmoMountMessageMapper.deleteDanmoMountDoorByPrintingIds(danmoDoorIdList);
        }

        List<Long> danmoWorksIdList = danmoMountMessageMapper.selectDanmoMountWorksList(danmoMountMessageId);
        if (CollectionUtils.isNotEmpty(danmoWorksIdList)) {
            danmoMountMessageMapper.deleteDanmoMountWorksByPrintingIds(danmoWorksIdList);
        }
        List<Long> danmoInteriorPhotos = danmoMountMessageMapper.seletDanmoMountInteriorPhotos(danmoMountMessageId);
        if (CollectionUtils.isNotEmpty(danmoInteriorPhotos)) {
            danmoMountMessageMapper.deleteDanmoMountInteriorPhotos(danmoInteriorPhotos);
        }

        List<Long> danmoInteriorTypes = danmoMountMessageMapper.seletDanmoMountMountTypes(danmoMountMessageId);
        if (CollectionUtils.isNotEmpty(danmoInteriorTypes)) {
            danmoMountMessageMapper.deleteDanmoMountTypes(danmoInteriorTypes);
        }
    }

    /**
     * 批量删除装裱信息
     *
     * @param ids 需要删除的装裱信息主键
     * @return 结果
     */
    @Transactional
    @Override
    public Result deleteDanmoMountMessageByIds(Long[] ids) {
        danmoMountMessageMapper.deleteDanmoMountImagesByMountIds(ids);
        for (Long id : ids) {
            deleteOldRelate(id);
        }
        danmoMountMessageMapper.deleteDanmoMountMessageByIds(ids);
        return Result.success(ids, "删除成功");
    }

    private void deleteOldRelate(Long id) {
        danmoMountMessageMapper.deleteDanmoMountWorks(id);
        danmoMountMessageMapper.deleteDanmoMountDoors(id);
        danmoMountMessageMapper.deleteDanmoMountInteriorList(id);
        danmoMountMessageMapper.deleteDanmoMountTypeList(id);

    }

    /**
     * 删除装裱信息信息
     *
     * @param id 装裱信息主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteDanmoMountMessageById(Long id) {
        danmoMountMessageMapper.deleteDanmoMountImagesByMountId(id);
        return danmoMountMessageMapper.deleteDanmoMountMessageById(id);
    }

    @Override
    public Result danmoMountMessageByUserId(Long userId) {
        DanmoMountMessage danmoMountMessages = danmoMountMessageMapper.danmoMountMessageByUserId(userId);
        if (danmoMountMessages == null) {
            return Result.error("暂无信息");
        }
        danmoMountMessageMapper.selectDanmoMountMessageById(danmoMountMessages.getId());
        return Result.success(danmoMountMessageMapper.selectDanmoMountMessageById(danmoMountMessages.getId()));
    }

    @Override
    public Result danmoMountMessageByViews() {
        return Result.success(danmoMountMessageMapper.danmoMountMessageByViews());
    }

    /**
     * 新增装裱图片信息
     *
     * @param danmoMountMessage 装裱信息对象
     */
    public void insertDanmoMountImages(DanmoMountMessage danmoMountMessage) {
        List<DanmoMountImages> danmoMountImagesList = danmoMountMessage.getDanmoMountImagesList();
        Long id = danmoMountMessage.getId();
        if (StringUtils.isNotNull(danmoMountImagesList)) {
            List<DanmoMountImages> list = new ArrayList<DanmoMountImages>();
            for (DanmoMountImages danmoMountImages : danmoMountImagesList) {
                danmoMountImages.setMountId(id);
                list.add(danmoMountImages);
            }
            if (list.size() > 0) {
                danmoMountMessageMapper.batchDanmoMountImages(list);
            }
        }
    }
}
